<template>
  <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
    <Back :backOption="backOption" />
    <div class="h-full">
      <el-row :gutter="20" class="main-wrap">
        <el-col :span="10">
          <div class="col-title">切词结果：</div>
          <el-form
            ref="queryFormRef"
            :inline="true"
            :model="queryParams"
            class="table-form mt-15px"
            label-width="85px"
          >
            <el-form-item label="关键词" prop="name">
              <ns-input
                v-model="queryParams.name"
                class="!w-240px"
                clearable
                placeholder="请输入关键词"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="命中范围" prop="name">
              <el-input-number
                class="!w-100px"
                v-model="queryParams.min"
                :min="1"
                :max="2147483647"
                :step="1"
                :step-strictly="true"
                controls-position="right"
              />
              <span class="ml-15px mr-15px">至</span>
              <el-input-number
                class="!w-100px"
                v-model="queryParams.max"
                :min="1"
                :max="2147483647"
                :step="1"
                :step-strictly="true"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
              <el-button @click="add"> 新增 </el-button>
              <el-button @click="handleExport"> 导出 </el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-table
              height="550"
              ref="tableRef"
              v-loading="leftLoading"
              :data="tableList"
              row-key="id"
              border
            >
              <el-table-column type="selection" :reserve-selection="true" width="85" />
              <el-table-column prop="name" label="关键词" align="center" />
              <el-table-column prop="hitCount" label="命中次数" align="center" />
              <el-table-column prop="score" label="权重分数" align="center" />
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button link type="danger" @click="handleDelete(scope.row.id)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.page"
              :total="total"
              @pagination="getList"
            />
          </div>
        </el-col>
        <el-col :span="7">
          <div class="col-title"
            >不包含关键词的文档：<span class="num">{{
              centerTableList && centerTableList.length
            }}</span></div
          >
          <div class="rt-wrap mt-15px">
            <el-button type="primary" @click="analysisHandle(1)"> 开始分析 </el-button></div
          >
          <el-table
            height="550"
            v-loading="centerLoading"
            :data="centerTableList"
            row-key="id"
            border
          >
            <el-table-column prop="name" label="文件名称" align="center">
              <template #default="{ row }">
                <el-link @click="downloadFile(row.id, row.name)" type="primary"
                  >{{ row.name }}
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="7">
          <div class="col-title"
            >包含关键词的文档：<span class="num">{{
              rightTableList && rightTableList.length
            }}</span></div
          >
          <div class="rt-wrap mt-15px">
            <el-button type="primary" @click="analysisHandle(2)"> 开始分析 </el-button></div
          >
          <el-table
            height="550"
            v-loading="rightLoading"
            :data="rightTableList"
            row-key="id"
            border
          >
            <el-table-column prop="name" label="文件名称" align="center">
              <template #default="{ row }">
                <el-link @click="downloadFile(row.id, row.name)" type="primary"
                  >{{ row.name }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="wordsNum" label="词数" align="center" min-width="50px" />
            <el-table-column prop="count" label="次数" align="center" min-width="50px" />
          </el-table>
        </el-col>
      </el-row>
      <el-dialog
        :model-value="dialogVisible"
        width="500px"
        title="新增关键词"
        align-center
        @close="dialogVisible = false"
      >
        <el-form :model="addForm" ref="addFormRef">
          <el-form-item
            label="关键词"
            prop="name"
            :rules="[{ required: true, trigger: 'blur', message: '请输入关键词' }]"
          >
            <el-input v-model="addForm.name" clearable placeholder="请输入关键词" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="submitAdd" type="primary">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </template>
      </el-dialog>
      <div style="text-align: center">
        <el-button type="primary" @click="submit()" :disabled="formLoading">保存至特征库</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </div>
  </ContentWrap>
  <SelectType ref="selectTypeRef" @success="submit" />
</template>

<script setup lang="ts">
import {
  getKeywordResult,
  deleteKeywordResult,
  getNoKeywordFile,
  syncKeywordTask,
  addKeyWord,
  exportKeyWord
} from '@/api/develop/keywordTask'
import SelectType from './dialog/SelectType.vue'
import { useFilePreview } from '../file/useFilePreview'
import download from '@/utils/download'

import type { FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
const backOption = reactive({
  title: '切词结果'
})
const formLoading = ref(false)
const router = useRouter()
const { params } = useRoute()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const dialogVisible = ref(false)
const { downloadFile } = useFilePreview()
const addFormRef = ref()
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  min: undefined,
  max: undefined
})

const addForm = ref({ name: '' })

const total = ref(0) // 列表的总页数
const leftLoading = ref(false) // 列表的加载中（左边表格）
const centerLoading = ref(false) // 列表的加载中(中间表格)
const rightLoading = ref(false) // 列表的加载中(右边表格)

const tableList = ref([]) // 列表的数据(左边)
const centerTableList = ref([]) // 列表的数据(中间)
const rightTableList = ref([]) // 列表的数据(右边)

const queryFormRef = ref<FormInstance>() // 搜索的表单
const tableRef = ref<InstanceType<typeof ElTable>>()
const selectTypeRef = ref<InstanceType<typeof SelectType>>()

/** 查询列表 */
const getList = async () => {
  leftLoading.value = true
  try {
    const { count, data } = await getKeywordResult({
      ...toRaw(queryParams),
      taskId: params.rid
    })
    total.value = count
    tableList.value = data
  } finally {
    leftLoading.value = false
  }
}
async function handleExport() {
  const checkedIds = tableRef.value?.getSelectionRows().map((i: any) => i.id)
  try {
    if (checkedIds && checkedIds.length === 0) {
      await message.confirm('确定导出该查询条件下全部关键词？')
      const data = await exportKeyWord({
        taskId: params.rid,
        mix: queryParams.min,
        name: queryParams.name,
        max: queryParams.max
      })
      download.excel(data, '切词结果.xlsx')
      return
    }

    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    const data = await exportKeyWord({
      taskId: params.rid,
      ids: checkedIds,
      ...queryParams
    })
    download.excel(data, '切词结果.xlsx')
  } catch {
  } finally {
  }
}
async function submit(data?: any) {
  const checkedIds = tableRef.value?.getSelectionRows().map((i: any) => i.id)

  if (checkedIds && checkedIds.length === 0) {
    await message.confirm('请选择关键词')
    return
  }

  if (!!data) {
    formLoading.value = true
    selectTypeRef.value?.setBtnStatus(true)
    try {
      await syncKeywordTask({
        taskId: params.rid,
        resultIds: checkedIds,
        ...data
      })
      message.success(t('common.createSuccess'))
      selectTypeRef.value?.close()
    } finally {
      selectTypeRef.value?.setBtnStatus(false)
      formLoading.value = false
    }
  } else {
    selectTypeRef.value?.open()
  }
}

async function add() {
  addFormRef.value?.resetFields()
  dialogVisible.value = true
}
async function submitAdd() {
  const valid = await addFormRef.value?.validate()
  if (!valid) {
    return
  }
  const { code } = await addKeyWord({ ...addForm.value, taskId: params.rid })
  if (code == 200) {
    dialogVisible.value = false
    ElMessage.success('新增成功')
    getList()
  }
}
async function analysisHandle(type) {
  const checkedIds = tableRef.value?.getSelectionRows().map((i: any) => i.id)
  if (checkedIds && checkedIds.length === 0) {
    await message.confirm('请选择关键词')
    return
  }
  type == 2 ? (rightLoading.value = true) : (centerLoading.value = true)

  try {
    const data = await getNoKeywordFile({
      taskId: params.rid,
      resultIds: checkedIds.join(','),
      type
    })
    // 对包含关键字的文件增加词数与次数列
    if (data.fileList && type == 2) {
      data.fileList.forEach((item) => {
        item.wordsNum = checkedIds.length
        item.count = Object.values(data.map[item.id]).reduce((acc, val) => acc + val, 0)
      })
    }
    type == 2
      ? (rightTableList.value = data.fileList || [])
      : (centerTableList.value = data.fileList || [])
  } finally {
    type == 2 ? (rightLoading.value = false) : (centerLoading.value = false)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteKeywordResult(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleClose = () => {
  router.push({ name: 'DevelopKeyword' })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.min = undefined
  queryParams.max = undefined
  handleQuery()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.main-wrap {
  padding: 40px 20px;
}
.rt-wrap {
  height: 50px;
  display: flex;
  justify-content: flex-end;
}
.col-title {
  .num {
    color: #409eff;
    font-size: 19px;
  }
}
</style>
